package algutil.gmusic.appli;

import gmusic.filter.Mp3Filter;

import java.io.File;
import java.io.IOException;

import org.apache.log4j.Logger;
import org.jaudiotagger.audio.AudioFileIO;
import org.jaudiotagger.audio.exceptions.CannotReadException;
import org.jaudiotagger.audio.exceptions.CannotWriteException;
import org.jaudiotagger.audio.exceptions.InvalidAudioFrameException;
import org.jaudiotagger.audio.exceptions.ReadOnlyFileException;
import org.jaudiotagger.audio.mp3.MP3File;
import org.jaudiotagger.tag.FieldKey;
import org.jaudiotagger.tag.Tag;
import org.jaudiotagger.tag.TagException;

public class OrganiserMetallianRealease {

	private static final Logger log = Logger
			.getLogger(OrganiserMetallianRealease.class);

	public static void main(String[] args) throws CannotReadException,
			IOException, TagException, ReadOnlyFileException,
			InvalidAudioFrameException, CannotWriteException {

		java.util.logging.Logger.getLogger("org.jaudiotagger").setLevel(
				java.util.logging.Level.WARNING);

		File releaseDir = new File(
				"D:/perso/music/to_process/METALLIAN - 2012 Underground Militia 8");

		File[] mp3Files = releaseDir.listFiles(new Mp3Filter());

		for (int i = 0; i < mp3Files.length; i++) {
			File mp3File = mp3Files[i];
			processOneMp3(mp3File);
		}
	}

	private static void processOneMp3(File mp3File) throws CannotReadException,
			IOException, TagException, ReadOnlyFileException,
			InvalidAudioFrameException, CannotWriteException {

		MP3File f = (MP3File) AudioFileIO.read(mp3File);
		Tag tag = f.getTag();

		String band = tag.getFirst(FieldKey.ARTIST);
		band = band.trim().toUpperCase();

		tag.setField(FieldKey.ARTIST, "METALLIAN");
		tag.addField(FieldKey.DISC_NO, "1");
		String trackNumber = tag.getFirst(FieldKey.TRACK);
		tag.deleteField(FieldKey.TRACK_TOTAL);
		tag.setField(FieldKey.TRACK, trackNumber);
		String titre = tag.getFirst(FieldKey.TITLE);
		titre = band + " - " + titre;
		tag.setField(FieldKey.TITLE, titre);

		f.setTag(tag);
		f.commit();

		trackNumber = (trackNumber.length() > 1 ? "" : "0") + trackNumber;

		String nvNom = "METALLIAN - " + trackNumber + " " + titre + ".mp3";
		log.info("Nv Nom = " + nvNom);

		if (nvNom.equalsIgnoreCase(mp3File.getName())) {
			File tmpName = new File(mp3File.getParent() + File.separator + "_"
					+ mp3File.getName());
			mp3File.renameTo(tmpName);
			mp3File = tmpName;
		}
		mp3File
				.renameTo(new File(mp3File.getParent() + File.separator + nvNom));

	}
}
